import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { PrismaService } from 'src/services/prisma.service';
import { Tag } from '../../typing';
import { Prisma } from '@prisma/client';
import { CreateCommentDto } from './dto/create.dto';

@Injectable()
export class WebsiteService {
  constructor(private prisma: PrismaService) {}
  async getAllTags(): Promise<{ tags: Tag[]; total: number }> {
    const [tags, total] = await Promise.all([
      this.prisma.tags.findMany({
        select: {
          tag_id: true,
          tag_name: true,
        },
        orderBy: [{ tag_id: 'desc' }],
      }),
      this.prisma.tags.count(),
    ]);
    return {
      tags,
      total,
    };
  }

  async getArticles(
    page: number,
    pageSize: number,
    type: number,
    priorCreate: boolean,
  ) {
    const orderBy: Prisma.articlesOrderByWithRelationInput[] = priorCreate
      ? [{ create_time: 'desc' }]
      : [{ top_up: 'desc' }, { popular: 'desc' }, { create_time: 'desc' }];
    return await Promise.all([
      this.prisma.articles.findMany({
        skip: (page - 1) * pageSize,
        take: pageSize,
        where: {
          type,
        },
        orderBy,
      }),
      this.prisma.articles.count({
        where: {
          type,
        },
      }),
    ]);
  }

  getArticlInfo(articleId: number) {
    return this.prisma.articles.findUnique({
      where: {
        article_id: articleId,
      },
    });
  }

  async publishComment(newComment: CreateCommentDto) {
    try {
      const created = await this.prisma.comments.create({
        data: {
          comment_nickname: newComment.commentNickname,
          comment_avatar: newComment.commentAvatar ?? null,
          comment: newComment.comment,
          comment_email: newComment.commentEmail,
          website: newComment.website ?? '',
          article: { connect: { article_id: newComment.articleId } },
          parent: newComment.parentId
            ? { connect: { comment_id: newComment.parentId } }
            : undefined,
          replied_nickname: newComment.repliedNickname ?? null,
        },
      });
      return created;
    } catch (error) {
      throw new InternalServerErrorException('评论失败');
    }
  }

  async getCommentTree(articleId: number) {
    return await this.prisma.comments.findMany({
      where: { article_id: articleId, parent_id: null },
      orderBy: { create_time: 'desc' },
      include: {
        replies: { orderBy: { create_time: 'asc' } },
      },
    });
  }
}
